<?php


namespace app\admin\controller\article;


use app\admin\annotation\NoAuth;
use app\admin\annotation\UseAuth;
use app\admin\controller\BaseController;
use app\common\http\exception\AppException;
use app\common\library\FormDataValidate;
use app\common\model\ArticleCategory as Category;
use app\admin\validate\ArticleCategoryValidate as CategoryValidate;
use think\Db;

/**
 * Class CategoryController
 * @package app\admin\controller\article
 * @UseAuth(policy="ArticleCategory")
 */
class CategoryController extends BaseController
{
    /**
     * 文章分类列表
     * @return mixed
     * @route('admin/article/categories', 'get')
     * @NoAuth()
     */
    public function index()
    {
        $result = Category::order('sort', 'asc')
            ->select();

        return $this->success(['items'=>$result]);
    }


    /**
     * 文章分类详情
     * @param $id
     * @return mixed
     * @throws AppException
     * @route('admin/article/category/:id', 'get')
     */
    public function read($id)
    {
        $result = Category::where('id', $id)->find();
        if (!$result) {
            throw new AppException('记录不存在');
        }

        return $this->success($result);
    }


    /**
     * 新增 / 编辑文章分类
     * @return mixed
     * @throws AppException
     * @route('admin/article/category', 'post')
     */
    public function post()
    {
        $form = new FormDataValidate(CategoryValidate::class, $this->request->post('id') ? 'edit' : 'add');

        if ($form->id) {
            $data = Category::where('id', $form->id)->find();
            if (!$data) {
                throw new AppException('记录不存在');
            }
        } else {
            $data = new Category();
        }
        Db::transaction(function () use($data, $form) {
            $form->path = '';
            $data->save($form->toArray());

            if ($form->pid) {
                $path = Category::where('id', $form->pid)->value('path');
                $path .= $data->id . '/';
            } else {
                $path = '/0/' . $data->id . '/';
            }
            $data->save([
                'path'=>$path
            ]);

            $this->recordActionLog(sprintf('修改文章分类：%s', $data->name));
        });

        return $this->success($data);
    }


    /**
     * 删除文章分类
     * @return \think\Response|\think\response\Json
     * @route('admin/article/category', 'delete')
     */
    public function delete()
    {
        $id = $this->request->post('id/a');

//        Db::transaction(function () use($id) {
//            $list = Category::where('id', 'in', $id)->field('id,name')->select();
//            foreach ($list as $item) {
//                $this->recordActionLog(sprintf('删除文章分类：%s', $item->name));
//                $item->delete();
//            }
//        });

        return $this->success();
    }

}